using Admin2025.Application.DTOs;
using Backoffice.Application.Common;
using Backoffice.Domain.Entities.App;
using Backoffice.Domain.Repositories;
using BackOffice.Application.DTOs;
using Microsoft.EntityFrameworkCore;


namespace BackOffice.Application.Services;

public class RoleService : IRoleService
{
  private readonly IRepository<AppRole> _roleRepo;
  private readonly IRepository<AppRolePermission> _permissionRepo;
  public RoleService(IRepository<AppRole> roleRepo, IRepository<AppRolePermission> permissionRepo)
  {
    _roleRepo = roleRepo;
    _permissionRepo = permissionRepo;
  }
  public async Task<ApiResult> AssignPermissionToRoleAsync(Guid roleId, string permissionCode)
  {
    var role = await _roleRepo.GetByIdAsync(roleId);
    if (role == null)
    {
      return ApiResult.Fail("角色未找到",3002);
    }
    var permission = (await _permissionRepo.GetAllAsync()).FirstOrDefault(x => x.Code == permissionCode);
    if (permission == null)
    {
      return ApiResult.Fail( "权限未找到",3002);
    }
    await _roleRepo.UpdateAsync(role);
    return ApiResult.Success(role, "分配权限成功");
  }



  public async Task<ApiResult> CreateRoleAsync(CreateRoleDto createRoleDto)
  {
    var exists = (await _roleRepo.GetAllAsync()).Any(r => r.Name == createRoleDto.RoleName);
    if (exists)
    {
      return ApiResult.Fail("角色名已存在", 3001);
    }
    var role = new AppRole(createRoleDto.RoleName);
    await _roleRepo.CreateAsync(role);
    return ApiResult.Success(role, "创建角色成功");
  }

  public async Task<ApiResult> DeleteRoleAsync(Guid roleId)
  {
    var role = await _roleRepo.GetByIdAsync(roleId);
    if (role == null)
    {
      return ApiResult.Fail("角色未找到", 3002);
    }
    await _roleRepo.DeleteAsync(roleId);
    return ApiResult.Success(role, "删除角色成功");
  }

  public Task<ApiResult> DisableAsync(Guid roleId)
  {
    var role = _roleRepo.GetByIdAsync(roleId).Result;
    if (role == null)
    {
      return Task.FromResult(ApiResult.Fail("角色未找到",3002));
    }
    _roleRepo.UpdateAsync(role).Wait();
    return Task.FromResult(ApiResult.Success(role, "禁用角色成功"));

  }

  public Task<ApiResult> EnableAsync(Guid roleId)
  {
    var role = _roleRepo.GetByIdAsync(roleId).Result;
    if (role == null)
    {
      return Task.FromResult(ApiResult.Fail("角色未找到",3002));
    }
    _roleRepo.UpdateAsync(role).Wait();
    return Task.FromResult(ApiResult.Success(role, "启用角色成功"));

  }


  public Task<ApiResult> RemovePermissionFromRoleAsync(Guid roleId, string permissionCode)
  {
    var role = _roleRepo.GetByIdAsync(roleId).Result;
    if (role == null)
    {
      return Task.FromResult(ApiResult.Fail("角色未找到",3002));
    }
    var permission = _permissionRepo.GetAllAsync().Result.FirstOrDefault(x => x.Code == permissionCode);
    if (permission == null)
    {
      return Task.FromResult(ApiResult.Fail("权限未找到",3002));
    }
    _roleRepo.UpdateAsync(role).Wait();
    return Task.FromResult(ApiResult.Success(role, "移除权限成功"));

  }



  public async Task<ApiResult> UpdateRoleAsync(Guid roleId, CreateRoleDto createRoleDto)
  {
    var role = await _roleRepo.GetByIdAsync(roleId);
    if (role == null)
    {
      return ApiResult.Fail("角色未找到", 3002);
    }
    
    // 检查角色名是否已存在（排除当前角色）
    var exists = (await _roleRepo.GetAllAsync()).Any(r => r.Name == createRoleDto.RoleName && r.Id != roleId);
    if (exists)
    {
      return ApiResult.Fail("角色名已存在", 3001);
    }
    
    role.UpdateInfo(createRoleDto.RoleName, role.Description);
    await _roleRepo.UpdateAsync(role);
    return ApiResult.Success(role, "更新角色成功");
  }
  public async Task<ApiResult> SearchRolesAsync(RoleSearchDto dto)
  {
      var query = _roleRepo.Query();
      if (!string.IsNullOrEmpty(dto.Name))
          query = query.Where(r => r.Name.Contains(dto.Name));
      if (!string.IsNullOrEmpty(dto.Description))
          query = query.Where(r => r.Description != null && r.Description.Contains(dto.Description));
      if (!string.IsNullOrEmpty(dto.Code))
          query = query.Where(r => r.Code == dto.Code);
      var result = await query.ToListAsync();
      return ApiResult.Success(result);
  }
}